package com.zzyl.service.impl;

import cn.hutool.Hutool;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.LoginVo;
import lombok.RequiredArgsConstructor;
import org.assertj.core.util.Lists;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class MemberServiceImpl implements MemberService {

    private final WechatService wechatService;

    private final MemberMapper memberMapper;

    private final JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    /**
     * 小程序登录逻辑
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.调用微信api,根据code获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
        System.out.println("获取到openId：" + openid);

        //2.根据openid查询数据库,获取数据库实体对象
        Member member = memberMapper.getByOpenId(openid);

        //3.用户为空，将openid属性添加到实体对象中
        if (member == null) {
            member = Member.builder().openId(openid).build();
        }

        //4.调用微信api,根据phone_code获取用户绑定的手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
        System.out.println("获取到用户的手机号码：" + phone);

        //5.保存或修改用户
        saveOrUpdate(member, phone);

        //6.将id存入到Token并返回
        Map<String,Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getName());
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),jwtTokenManagerProperties.getTtl(),claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());

        return loginVo;
    }

    /**
     * 保存或修改用户
     *
     * @param member
     * @param phone
     */
    private void saveOrUpdate(Member member, String phone) {
        //1.判断取到的手机号码和数据库里面的手机号码是否一致
        if (!StringUtils.equals(member.getPhone(),phone)) { //这里不能直接用member.getPhone调用equals方法，因为phone的值还没有被初始化，会报空指针异常
            //手机号不一致，将该手机号添加到实体对象中
            member.setPhone(phone);
        }

        //2.判断id存在,更新用户信息
        if (!ObjectUtil.isEmpty(member.getId())) {
            memberMapper.update(member);
        }else {
            //3.保存新的用户
            memberMapper.save(member);
        }

        String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                + StringUtils.substring(member.getPhone(), 7);
        member.setName(nickName);
    }
}
